<template>
  <div>
    <!-- 查询参数及按钮部分 -->
    <div class="filter-container">
      <el-dialog
        v-dialogDrag
        :close-on-click-modal="false"
        :title="dialogStatus"
        :visible.sync="dialogEditFormVisible"
        style="padding: 0px"
        width="60%"
      >
        <el-form
          ref="dataForm"
          class="dialog-Backgroundcolor"
          :model="listQuery"
          label-position="right"
          label-width="120px"
        >
          <el-row>
            <el-row style="margin-left: -30px">
              <!-- <el-col :span="8">
                <el-form-item label="人员类别：">
                  <el-select v-model="formData.state" class="filter-item" placeholder="--请选择--" style="width:100%" >
                    <el-option label="全部人员" value="" />
                    <el-option label="在职人员" value="3" />
                    <el-option label="离休人员" value="1" />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item label="身份证号码：">
                  <el-input v-model="formData.idenNo" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名：">
                  <el-input v-model="formData.personName" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-left: -30px">
              <!-- <el-col :span="10"> -->
              <el-form-item label="工资项：">
                <el-select
                  v-model="formData.salaryColum"
                  class="filter-item"
                  placeholder="--请选择--"
                  clearable
                >
                  <el-option
                    v-for="item in salaryNames"
                    :key="item.value"
                    :label="item.key"
                    :value="item.value"
                  /> </el-select
                >&nbsp;
                <el-input-number
                  v-model="formData.salaryColumMin"
                  :controls="false"
                  class="filter-item"
                />
                <el-input-number
                  v-model="formData.salaryColumMax"
                  :controls="false"
                  class="filter-item"
                />
              </el-form-item>
            </el-row>
            <el-row style="margin-left: -30px">
              <el-col :span="8">
                <el-form-item label="请选择科室：" prop="deptId">
                    <el-select
                      ref="selectReport"
                      v-model="formData.deptName"
                      class="filter-item"
                      placeholder="--请选择--"
                      :clearable="clearable"
                      @clear="clearHandle"
                    >
                      <el-option
                        :value="formData.deptId"
                        :label="formData.deptName"
                        style="
                          width: 300px;
                          height: 200px;
                          overflow: auto;
                          background-color: #fff;
                        "
                      >
                        <el-tree
                          :data="listTree"
                          :accordion="accordion"
                          :props="defaultProps"
                          :node-key="defaultProps.id"
                          :default-expanded-keys="defaultExpandedKey"
                          @node-click="handleNodeClick"
                        />
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="人员编码：">
                  <el-input v-model="formData.personnelCode" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-button
              type="primary"
              style="float: right"
              @click="handleFilter"
            >
              查询
            </el-button>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <el-row>
      <el-col :span="4">
        <el-select
          v-model="formData.salaryType"
          class="filter-item"
          placeholder="工资类型"
          @change="handleFilter"
        >
          <el-option label="全部工资类型" value="" />
          <el-option
            v-for="item in salaryTypes"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="formData.state"
          class="filter-item"
          placeholder="人员类型"
          style="width: 100%"
          @change="handleFilter"
        >
          <el-option label="全部人员类型" value="" />
          <el-option label="在职人员" value="3" />
          <el-option label="离休人员" value="1" />
        </el-select>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px">
      <el-col :span="24">
        <div>单位名称：{{ unitName }}</div>
        <span style="font-size: 16px"
          >实发合计：{{
            Number(reallySendSalarySum)
              .toFixed(2)
              .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
          }}元</span
        >
        <span style="font-size: 16px"
          >（其中：在职合计：{{
            Number(workSalarySum)
              .toFixed(2)
              .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
          }}元</span
        >，
        <span style="font-size: 16px"
          >离休合计：{{
            Number(retireSalarySum)
              .toFixed(2)
              .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
          }}元）</span
        ><br />
        <span style="font-size: 16px">在编人员：{{ personTotal }}人</span>
        <span style="font-size: 16px">（其中：在职：{{ workTotal }}人</span>，
        <span style="font-size: 16px">离休：{{ retireTotal }}人）</span>；
        <span style="font-size: 16px">单位增员：{{ unitPlusTotal }}人</span>
        <span style="font-size: 16px">（其中：在职：{{ workPlusTotal }}人</span
        >，
        <span style="font-size: 16px">离休：{{ retirePlusTotal }}人）</span>；
        <span style="font-size: 16px">单位减员：{{ unitMinusTotal }}人</span>
        <span style="font-size: 16px">（其中：在职：{{ workMinusTotal }}人</span
        >，
        <span style="font-size: 16px">离休：{{ retireMinusTotal }}人）</span>
      </el-col>
      <!-- <el-col v-if="this.tabPane === '-1'" :span="1">
        <el-link type="primary" @click="openAuditExplain">
          <span>退回说明</span>
        </el-link>
      </el-col> -->
    </el-row>
    <!-- 表格部分 -->
    <vxe-table
      ref="singalTable"
      v-loading="listLoading"
      border="inner"
      :data="list"
      show-overflow
      show-header-overflow
      show-footer-overflow
      :scroll-x="{enabled: true, gt: 100, oSize: 100}"
      :scroll-y="{enabled: true, gt: 100, oSize: 100}"
      :sort-config="{trigger: 'cell', orders: ['desc', 'asc', null]}"
      show-footer
      :footer-method="footerMethod"
      row-id="personId"
      :tree-config="{ children: 'children' }"
      fit
      :height="tableHeight"
      class="my-test"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <vxe-table-column lable="" tree-node type="seq"  min-width="80" fixed="left" ></vxe-table-column>
      <vxe-table-column label="" min-width="50" fixed="left">
        <template v-slot:header>
          <vxe-checkbox
            v-model="checkAll"
            :indeterminate="indeterminate"
            @change="handleCheckAll"
          />
        </template>
        <template v-slot="scope">
          <vxe-checkbox
            v-if="scope.row.index && scope.row.index !== '0'"
            v-model="scope.row.check"
            @change="handleCheck"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column width="30" fixed="left">
        <template slot-scope="{ row }">
          <i v-if="row.existsFile === 1" class="el-icon-paperclip file-logo" />
        </template>
      </vxe-table-column>
      <!-- <vxe-table-column title="工资月份" min-width="80" fixed="left">
        <template slot-scope="{row}">
          <span :style="{ color: row.different === 1 ? 'red':'black' }">{{ row.currentMonth }}</span>
        </template>
      </vxe-table-column> -->
      <vxe-table-column
        title="科室"
        min-width="100"
        field="deptId"
        fixed="left"
        sortable
      >
        <template slot-scope="{ row }">
          <span :style="{ color: row.different === 1 ? 'red' : 'black' }">{{
            row.deptId | deptNameFilter(that)
          }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column
        title="人员编码"
        min-width="100"
        field="personnelCode"
        fixed="left"
        sortable
      >
        <template slot-scope="{ row }">
          <span :style="{ color: row.different === 1 ? 'red' : 'black' }">{{
            row.personnelCode
          }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column
        title="姓名"
        min-width="100"
        field="personName"
        fixed="left"
        sortable
      >
        <template slot-scope="{ row }">
          <el-link type="primary" @click="viewInfo(row)">
            <span :style="{ color: row.different === 1 ? 'red' : 'black' }">{{
              row.personName
            }}</span>
          </el-link>
        </template>
      </vxe-table-column>
      <vxe-table-column
        title="身份证号"
        min-width="200"
        field="idenNo"
        fixed="left"
        sortable
      >
        <template slot-scope="{ row }">
          <span :style="{ color: row.different === 1 ? 'red' : 'black' }">{{
            row.idenNo
          }}</span>
        </template>
      </vxe-table-column>      
      <vxe-table-column v-for="item in columnNames" :field="item.split('_')[0]" :key="item" :title="item.split('_')[0] | salaryNameFilter(that)" align="right" min-width="150">
        <template slot-scope="{ row }">
          <!--判断当前行是否处于编辑状态，并且判断该字段是否是计算值-->
          <div
            :style="{
              float: 'right',
              color:
                (row[item.split('_')[0]] !==
                  row[item.split('_')[0] + '_history'] ||
                  (row.s1 === 0 && row.s1_history === 0)) &&
                row.personName !== '合计'
                  ? 'red'
                  : 'black',
            }"
          >
            <vxe-input
              v-if="row.isOperate && item.split('_')[1] !== 'compute'"
              v-model="row['input' + item.split('_')[0]]"
              placeholder=""
              type="float"
              align="right"
              min="0"
              max="99999999"
              clearable
              @keyup.enter.native="nextInput($event)"
            />
            <span v-if="row.isOperate && item.split('_')[1] === 'compute'">{{
              Number(row["input" + item.split("_")[0]])
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            }}</span>
            <!--获取不带后缀的字段名-->
            <span v-if="!row.isOperate">{{
              Number(row[item.split("_")[0]])
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            }}</span>
          </div>
        </template>
      </vxe-table-column>
    </vxe-table>
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="导入"
      :visible.sync="dialogImportFormVisible"
      width="29%"
    >
      <el-upload
        class="upload-demo"
        drag
        style="padding-left: 2px"
        action="#"
        list-type="multipart/form-data"
        accept=".xls,.xlsx"
        :show-file-list="false"
        :http-request="uploadExcel"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip" />
      </el-upload>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="退回说明"
      :visible.sync="auditFormVisible"
      width="30%"
      max-height="500px"
    >
      <el-form
        ref="auditForm"
        :model="auditFormData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col>
            <el-input
              v-model="auditFormData.auditExplain"
              type="textarea"
              :rows="4"
              maxlength="500"
            />
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="请选择单位"
      :visible.sync="dialogVerifyFormVisible"
      style="padding: 0px"
      width="50%"
    >    
     <el-row>
       <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
             
            @click="dialogVerifyFormVisible = false"         
          >
            取消
          </el-button> 
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            
             @click="submitAll"
          >
            提交
          </el-button>
        </el-row>
                  <el-tree
                    ref="tree"
                    :data="agencyTreeData"
                    show-checkbox                  
                    node-key="id"                  
                    :props="defaultProp">
                  </el-tree>
    </el-dialog>
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <Enclosure ref="enc" :middle-table-code="2" />
    <UnitSalaryReportChildrenEditAll
      v-if="handleEditAllShow"
      :dept-names="deptNames"
      :column-names="columnNames"
      :select-data="checkList"
      :salary-names="salaryNames"
      :compute-formula="computeFormula"
      @close="editAllClose"
    />
    <PersonSalaryInfo ref="personSalaryInfo" />
    <ApprovalProcess ref="app" />
  </div>
</template>
<script>
import {
  querySalaryNameDict,
  generateFormula,
  queryReallySendSalarySumAndPersonTotal,
  queryColumnName,
  queryUnitSalaryReportPage,
  submitData,
  submit,
  rejectSubmit,
  rejectEdit,
  outPutSalaryReportList,
  Import,
  verfityExistNoFilePerson,
  JudgePersonBank
} from "@/api/unitSalaryReport/unitSalaryReport";
import { getSalaryType, getConfigCtrlByTypeMof } from "@/api/baseInfo";
import { queryAgencyNameAndState } from "@/api/unitInformationMaintenance/unitInformationEdit";
import {
  getDepartmentList,
  getDepartmentTree,
} from "@/api/unitInformationMaintenance/internalOrganizationMaintenance";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import tableEmpty from "@/components/table/empty";
import Enclosure from "@/components/Enclosure";
import PersonSalaryInfo from "@/components/personSalaryInfo/personSalaryInfo";
import {
  getAgencyVerifyByAgencyId,
  getPaidWagesCount,
  getUnreviewedPersonCount,
  getsubmitable
} from "@/api/agencyVerify";
import { queryPersonFileNum } from "@/api/personInfoMaintenance/personChangeEdit";
import ApprovalProcess from "@/components/ApprovalProcess/ApprovalProcess";
import UnitSalaryReportChildrenEditAll from "./unitSalaryReportChildrenEditAll";
import { getFirstAuthAgencyData,  getAuthAgencyTrees, getIsLeafIds } from '@/api/baseInfo';


export default {
  name: "UnitSalaryReportChildren",
  components: {
    ApprovalProcess,
    Pagination,
    tableEmpty,
    Enclosure,
    PersonSalaryInfo,
    UnitSalaryReportChildrenEditAll,
  },
  filters: {
    deptNameFilter(value, that) {
      const deptNames = that.deptNames;
      for (const item of deptNames) {
        if (value === item.code) {
          return item.name;
        }
      }
    },
    // 工资项滤器
    salaryNameFilter(value, that) {
      const salaryNames = that.salaryNames;
      for (const item of salaryNames) {
        if (item.value === value) {
          return item.key;
        }
      }
    },
  },
  props: ["tabPane", "treeData"],
  data() {
    return {
      number: 1,
      tableHeight: null,
      dialogStatus: "",
      dialogEditFormVisible: false,
      dialogImportFormVisible: false,
      dialogVerifyFormVisible: false,
      ifSubmitAll: 0,
      count: 0,
      formStatus: "",
      configCtrl: "1",
      that: this,
      reallySendSalarySum: "0.00",
      workSalarySum: "0.00",
      retireSalarySum: "0.00",
      personTotal: "0",
      workTotal: "0",
      retireTotal: "0",
      unitMinusTotal: "0",
      unitPlusTotal: "0",
      retireMinusTotal: "0",
      workMinusTotal: "0",
      retirePlusTotal: "0",
      workPlusTotal: "0",
      openenclosure: true,
      accordion: false,
      isLeafIds: [],
      list: [],
      judgePersonBank: [],
      submitList: [],
      submitPersonIds: [],
      salaryTypes: [],
      total: 0,
      listLoading: false,
      listTree: null,
      defaultExpandedKey: [],
      clearable: true,
      treeQuery: '',
      agencyTreeData: [],
      firstAuthAgencyData: {},
      personnelCode: '',
      defaultProp: {
        id: "id",
        children: "children",
        label: "label",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      listQuery: {
        page: 1,
        limit: 500,
        flag: 'all',
        menuid: this.$router.currentRoute.meta.menuid
      },
      formData: {
        state: "", // 人员类别
        idenNo: "", // 身份证号码
        personName: "", // 姓名
        salaryType: "", //人员类型
        salaryColum: "",
        salaryColumMin: "",
        salaryColumMax: "",
        id: "",
        state: "",
        agencyCode: this.$store.getters.userInfo.agencyCode,
        agencyName: "",
        agencyId: "",
        deptId: "",
        deptName: "",
        idenNo: "",
        personnelCode: ''
      },
      columnNames: [], // 动态表头
      salaryNames: [],
      deptNames: [],
      unitName: "预算单位",
      agencyName: "",
      agencyId: null,
      menuid: this.$router.currentRoute.meta.menuid,
      isSubmitInAgency: 0,
      salaryVerifiedInAgencyCode: "0",
      checkAll: false,
      indeterminate: false,
      checkList: [],
      changeList: {},
      inputList: {}, // 缓存最后一次输入正确的值，id{id}_inputs1 大括号内的id恢替换成id的数值
      computeFormula: [],
      auditFormVisible: false,
      auditFormData: {
        auditExplain: "",
      },
      handleEditAllShow: false,
      submitablenum: 0
    };
  },
  watch: {
    treeQuery(val) {
      this.$refs.tree.filter(val)
    },
    submitList: {
      immediate: true,
      deep: true,
      handler(val) {
        this.calculate(val);
      },
    },
    // 表格的数据数组
    // list(val) {
    //   this.doLayout()
    // },
    treeData(val) {
      if (val && val.isleaf === "1") {
        this.unitName = val.label.split("-")[1];
        this.agencyId = val.id;
        this.handleTree(val);
      }
    },
  },
  mounted() {   
    this.getTbHeight();
  },
  beforeMount() {
    window.addEventListener("resize", this.getTbHeight);
  },
  created() {  
    this.listQuery.flag = this.tabPane;
    if (this.treeData && this.treeData.isleaf === "1") {
      this.unitName = this.treeData.label.split("-")[1];
      this.agencyId = this.treeData.id;
      this.initDict();
      this.queryAgencyNameAndState();
      this.handleFilter();
      this.getAgencyVerifyByAgencyId();
    }
    this.getTreeData();
    this.getFirstAuthAgencyData();
    this.getIsLeafIds();
  },
  methods: {
    getIsLeafIds(){
      getIsLeafIds().then(res =>{
        this.isLeafIds = res.data;
      })
    },
    getFirstAuthAgencyData() {
      getFirstAuthAgencyData().then(res => {
        this.$emit('getFirstAuthAgencyData', res.data)
      })
    },

    //获取未审核单位树
    getTreeData() {
      this.count = 0;
      getAuthAgencyTrees().then(response => {
        this.agencyTreeData = response.data;
      })
    },
    // 树查询过滤
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 选择树
    handleNodeClicks(data) {
      this.$emit('handleTreeQuery', data)
      // if (!Object.prototype.hasOwnProperty.call(data, 'children')) {
      // }
    },
    editAllClose($event) {
      this.handleEditAllShow = false;
      if ($event === 2) {
        this.handleFilter();
      }
    },
    processnode() {
      this.$refs.app.getList(this.agencyId);
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 350;
    },
    /* 重新渲染table组件 */
    // doLayout() {
    //   this.$nextTick(() => {
    //     this.$refs.singalTable.doLayout()
    //   })
    // },
    // 获取审核意见
    getAgencyVerifyByAgencyId() {
      getAgencyVerifyByAgencyId(this.listQuery.agencyId).then((response) => {
        this.auditFormData.auditExplain = response.data.auditExplain;
      });
    },
    // 打开审核意见
    openAuditExplain() {
      this.auditFormVisible = true;
    },
    // 查询
    query() {
      this.clearHandle();
      this.dialogStatus = "查询";
      this.dialogEditFormVisible = true;
    },
    calculate(submitList) {
      // 获取每一行的数据进行计算
      for (const submit of submitList) {
        for (const computeFormula of this.computeFormula) {
          const meritPayCode = computeFormula.meritPayCode.split(",");
          if (meritPayCode.includes(submit.meritPayCode)) {
            const formula = computeFormula.computeFormula;
            const decimalPlace = computeFormula.decimalPlace
            const equation = formula.split("=");
            const answer = equation[0];
            const args = equation[1].split(",");
            let calc = "";
            for (let arg of args) {
              if (arg.startsWith("&") && arg.endsWith("&")) {
                arg = arg.substring(1, arg.length - 1);
                if (arg !== "null") {
                  calc +=
                    (submit["input" + arg] === "") |
                    (submit["input" + arg] === undefined)
                      ? "0"
                      : submit["input" + arg];
                } else {
                  calc += 0;
                }
              } else {
                calc += arg;
              }
            }
            submit["input" + answer] = Number(
              this.$math.round(this.$math.evaluate(calc), decimalPlace)
            );
          }
        }
      }
    },
    querySalaryNameDict() {
      Object.assign(this.listQuery, this.formData);
      this.listQuery["agencyId"] = this.agencyId;
      // 查询工资项名称
      querySalaryNameDict(this.listQuery)
        .then((res) => {
          this.salaryNames = res.data;
        })
        .catch(() => {
          this.salaryNames = [];
        });
    },

    // 初始化字典
    initDict() {
      //获取工资类型
      getSalaryType().then((response) => {
        this.salaryTypes = Object.assign({}, response.data);
      });
      // 查询工资项名称
      querySalaryNameDict(this.listQuery)
        .then((res) => {
          this.salaryNames = res.data;
        })
        .catch(() => {
          this.salaryNames = [];
        });
      // 查询部门名称
      getDepartmentList({ agencyId: this.agencyId })
        .then((res) => {
          this.deptNames = res.data;
        })
        .catch(() => {
          this.deptNames = [];
        });
      // 生成计算公式
      generateFormula(this.agencyId)
        .then((res) => {
          this.computeFormula = res.data;
        })
        .catch(() => {
          this.computeFormula = [];
        });
      //获取是否上传附件做校验
      getConfigCtrlByTypeMof("fileVerify").then((response) => {
        this.configCtrl = response.data;
      });
    },

    queryAgencyNameAndState() {
      // 查询机构名称
      return queryAgencyNameAndState(this.agencyId)
        .then((res) => {
          this.agencyName = res.data.agencyName;
          this.isSubmitInAgency = res.data.isSubmitInAgency;
          this.salaryVerifiedInAgencyCode = res.data.salaryVerifiedInAgencyCode;
        })
        .catch(() => {
          this.agencyName = "";
          this.isSubmitInAgency = 0;
          this.salaryVerifiedInAgencyCode = "0";
        });
    },

    queryReallySendSalarySumAndPersonTotal() {
      queryReallySendSalarySumAndPersonTotal(this.agencyId, 0)
        .then((res) => {
          this.reallySendSalarySum = res.data.reallySendSalarySum;
          this.workSalarySum = res.data.workSalarySum;
          this.retireSalarySum = res.data.retireSalarySum;
          this.personTotal = res.data.personTotal;
          this.workTotal = res.data.workTotal;
          this.retireTotal = res.data.retireTotal;
          this.unitMinusTotal = res.data.unitMinusTotal;
          this.unitPlusTotal = res.data.unitPlusTotal;
          this.retireMinusTotal = res.data.retireMinusTotal;
          this.workMinusTotal = res.data.workMinusTotal;
          this.retirePlusTotal = res.data.retirePlusTotal;
          this.workPlusTotal = res.data.workPlusTotal;
        })
        .catch(() => {
          this.reallySendSalarySum = "0.00";
          this.workSalarySum = "0.00";
          this.retireSalarySum = "0.00";
          this.personTotal = "0";
          this.workTotal = "0";
          this.retireTotal = "0";
          this.unitMinusTotal = "0";
          this.unitPlusTotal = "0";
          this.retireMinusTotal = "0";
          this.workMinusTotal = "0";
          this.retirePlusTotal = "0";
          this.workPlusTotal = "0";
        });
    },

    // 动态获取表头
    getColumnNames() {
      Object.assign(this.listQuery, this.formData);
      this.listQuery["agencyId"] = this.agencyId;
      queryColumnName(this.listQuery)
        .then((response) => {
          this.columnNames = response.data;
        })
        .catch(() => {
          this.columnNames = [];
        });
    },
    handleTree(data) {
      this.initDict();
      this.queryAgencyNameAndState();
      this.handleFilter();
      this.getAgencyVerifyByAgencyId();
    },
    // 查询
    handleFilter() {
      this.getTree()
      this.listQuery.page = 1;
      // this.listQuery.limit = 10
      this.getList();
      this.dialogEditFormVisible = false;
    },

    initData() {
      this.checkAll = false;
      this.indeterminate = false;
      this.listLoading = false;
      this.submitList = [];
      this.submitPersonIds = [];
      this.checkList = [];
      this.inputList = {};
    },

    // 获取数据
    getList() {
      this.getTreeData();
      this.getFirstAuthAgencyData();
      this.listLoading = true;
      this.getColumnNames();
      this.queryReallySendSalarySumAndPersonTotal();
      Object.assign(this.listQuery, this.formData);
      this.listQuery["agencyId"] = this.agencyId;
      queryUnitSalaryReportPage(this.listQuery)
        .then((response) => {
          this.list = response.data.rows;
          for (const item of this.list) {
            if (item.children) {
              // table中的row-key需要id不为空且不可重复
              item.children[0].personId += "noRepeat";
            }
            this.$set(item, "check", false);
          }
          this.total = response.data.total;
          this.initData();
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.initData();
        });
    },
    // 批量修改
    handleEditAll() {
      if (this.checkList.length === 0) {
        this.$message({
          message: "请选择数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        return;
      }
      this.handleEditAllShow = true;
    },
    // 编报，修改
    handleEdit() {
      this.queryAgencyNameAndState().then(() => {
        // 送审后不可编辑
        if (this.isSubmitInAgency === 1) {
          this.$message({
            message: "当前单位数据已送审，不可编辑！",
            type: "warning",
            showClose: true,
            duration: 4000,
          });
          return;
        }
        const selection = this.checkList;
        if (selection.length === 0) {
          this.$message({
            message: "请选择数据",
            type: "warning",
            showClose: true,
            duration: 4000,
          });
          return;
        }
        for (let name of this.columnNames) {
          name = name.split("_")[0];
          for (const item of selection) {
            let value = "";
            if (item[name] !== 0) {
              value = item[name];
            }
            this.$set(item, "input" + name, value);
          }
        }
        for (const item of selection) {
          if (!this.submitPersonIds.includes(item.personId)) {
            this.$set(item, "isOperate", true);
            this.$set(item, "columnNames", this.columnNames.join(","));
            this.submitPersonIds.push(item.personId);
            this.submitList.push(item);
          }
        }
        this.calculate(this.submitList);
      });
    },
    // 取消修改
    handleCancelEdit() {
      const selection = this.checkList;
      if (selection.length === 0) {
        this.$message({
          message: "请选择数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        return;
      }
      const submitPersonIds = this.submitPersonIds;
      const submitList = this.submitList;
      for (const item of selection) {
        this.$set(item, "isOperate", false);
        for (let i = 0; i < submitPersonIds.length; i++) {
          if (item.personId === submitPersonIds[i]) {
            submitPersonIds.splice(i, 1);
            i--;
            break;
          }
        }
        for (let j = 0; j < submitList.length; j++) {
          if (item === submitList[j]) {
            submitList.splice(j, 1);
            j--;
            break;
          }
        }
      }
    },
    // 保存
    handleSave() {
      const submitList = this.submitList;
      if (submitList.length === 0) {
        this.$message({
          message: "没有可保存的数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleSaveBtnLoading");
        return;
      }
      const personIds = [];
      for (const submit of submitList) {
        personIds.push(submit.personId);
      }
      // 校验附件
      const params = {};
      params["personId"] = personIds.join(",");
      params["agencyId"] = this.agencyId;
      params["operateType"] = "2";
      queryPersonFileNum(params)
        .then((response) => {
          // this.$confirm('确定保存吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          for (const submit of submitList) {
            for (let name of this.columnNames) {
              name = name.split("_")[0];
              submit[name] = submit["input" + name];
              // this.$delete(submit, 'input'+name);
            }
          }

          submitData(submitList)
            .then(() => {
              if (response.data === 0) {
                this.$message({
                  showClose: true,
                  message: "保存成功！",
                  type: "success",
                  duration: 4000,
                  // onClose: this.appendixOpen //如果存在未上传附件的人员，则打开附件管理让其上传附件
                });
              } else {
                this.$message({
                  message: "保存成功",
                  type: "success",
                  showClose: true,
                  duration: 4000,
                });
              }
              this.getList();
              this.$emit("handleSaveBtnLoading");
            })
            .catch(() => {
              this.$emit("handleSaveBtnLoading");
            });
        })
        .catch(() => {
          this.$emit("handleSaveBtnLoading");
        });
      // }).catch(() => {
      //   this.$emit('handleSaveBtnLoading')
      // })
    },

    // 撤销修改
    handleRejectEdit() {
      const selection = this.checkList;
      if (selection.length !== 1) {
        this.$message({
          message: "请选择一条数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleRejectEditBtnLoading");
        return;
      }
      // this.$confirm('确定撤销修改吗？', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      rejectEdit(selection[0])
        .then((res) => {
          this.$message({
            message: "撤销修改成功",
            type: "success",
            showClose: true,
            duration: 4000,
          });
          this.getList();
          this.$emit("handleRejectEditBtnLoading");
        })
        .catch(() => {
          this.$emit("handleRejectEditBtnLoading");
        });
      // })
      // .catch(() => {
      //   this.$emit('handleRejectEditBtnLoading')
      // })
    },

      //显示批量送审弹窗
    handleSubmitAll(){
      this.dialogVerifyFormVisible = true
    },

      //批量送审
    submitAll() {
      this.dialogVerifyFormVisible = false
      this.$emit("trueSubmitBtnLoadings");
      const selections = this.$refs.tree.getCheckedKeys();
      this.isLeafIds.push('0');
      this.isLeafIds.forEach((item) => {
        for (let i = 0; i < selections.length; i++) {
          if (item==selections[i]) {
          selections.splice(i,1);
         }
        }
      });
      this.ifSubmitAll = selections.length;
       if (selections.length == 0) {
        this.$message({
          message: "没有可送审的数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleSubmitBtnLoadings");
        return;
      }
      for (let i = 0; i < selections.length; i++) {
          let agencyId = selections[i]
          this.handleSubmits(agencyId);
        }     
    },

    // 批量送审
    handleSubmits(agencyId) {
      getPaidWagesCount(agencyId)
        .then((count) => {
          if (count !== 0) {
            this.$message({
              message: "有应发工资为0人员",
              type: "warning",
              showClose: true,
              duration: 4000,
            });
            this.getList();
            this.$emit("handleSubmitBtnLoadings");           
            return;
          }
          getUnreviewedPersonCount(agencyId)
            .then((count1) => {
              if (count1 !== 0) {
                this.$message({
                  message: "有未经审核人员",
                  type: "warning",
                  showClose: true,
                  duration: 4000,
                });
                this.getList();
                this.$emit("handleSubmitBtnLoadings");
                return;
              }
              verfityExistNoFilePerson(agencyId)
                .then((res) => {
                  if (res.data && this.configCtrl == "1") {
                    this.$message({
                      showClose: true,
                      message: "存在未上传附件的人员",
                      type: "warning",
                      duration: 4000,
                    });
                    this.getList();
                    this.$emit("handleSubmitBtnLoadings");
                    return;
                  }
                  const params = {
                    agencyId,
                    menuid: this.menuid,
                  };
                  this.count+=1;
                  submit(params)
                    .then((res) => {
                      if(this.count==this.ifSubmitAll){
                        this.$message({
                        message: "送审成功",
                        type: "success",
                        showClose: true,
                        duration: 4000,
                      });
                      this.getList();
                      this.$emit("handleSubmitBtnLoadings");
                      }                      
                    })
                    .catch(() => {
                      this.getList();
                      this.$emit("handleSubmitBtnLoadings");
                    });
                })
                .catch(() => {
                  this.getList();
                  this.$emit("handleSubmitBtnLoadings");
                });
            })
            .catch(() => { 
              this.getList();
              this.$emit("handleSubmitBtnLoadings");
            });
        })
        .catch(() => { 
          this.getList();
          this.$emit("handleSubmitBtnLoadings");
        });
    },

    // 送审
    handleSubmit() {
      if (this.total === 0) {
        this.$message({
          message: "没有可送审的数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleSubmitBtnLoading");
        return;
      }

      getsubmitable(this.agencyId).then((response) => {
        this.submitablenum = response.data
        if(this.submitablenum === 0){
        this.$message({
        showClose: true,
        message: '该单位不允许上报',
        type: 'warning',
        duration: 4000
        })
        this.$emit("handleSubmitBtnLoading");
        return
        }else{  

        getPaidWagesCount(this.agencyId)
          .then((count) => {
            if (count !== 0) {
              this.$message({
                message: "有应发工资为0或实发工资小于0人员",
                type: "warning",
                showClose: true,
                duration: 4000,
              });
              this.$emit("handleSubmitBtnLoading");
              return;
            }
            getUnreviewedPersonCount(this.agencyId)
              .then((count1) => {
                if (count1 !== 0) {
                  this.$message({
                    message: "有未经审核人员",
                    type: "warning",
                    showClose: true,
                    duration: 4000,
                  });
                  this.$emit("handleSubmitBtnLoading");
                  return;
                }
                verfityExistNoFilePerson(this.agencyId)
                  .then((res) => {
                    if (res.data && this.configCtrl == "1") {
                      this.$message({
                        showClose: true,
                        message: "存在未上传附件的人员",
                        type: "warning",
                        duration: 4000,
                      });
                      this.$emit("handleSubmitBtnLoading");
                      return;
                    }
                    JudgePersonBank(this.agencyId)
                        .then((res)=>{
                        if (res.data == null ||  res.data == '') {
                            this.$message({
                            message: "请编辑单位信息发卡银行",
                            type: "warning",
                            showClose: true,
                            duration: 4000,
                            });
                            this.$emit("handleSubmitBtnLoading");
                        return;
                        }
                        this.judgePersonBank = res.data;
                        const arr=[]
                        let cardBank = '';
                          for(let i=0;i< this.judgePersonBank.length;i++){
                              if(this.judgePersonBank[i].salaCardBank == '1'){
                                this.cardBank = '1'
                                arr.push(this.judgePersonBank[i].personName)
                              }
                          }
                            if(this.cardBank == '1'){
                            this.$message({
                              showClose: true,
                              message:  arr+ ",存在银行信息不匹配人员",
                              type: "warning",
                              duration: 4000,
                            });
                            this.$emit("handleSubmitBtnLoading");
                            return;
                          }
                          
                        
                              // this.$confirm('确定送审吗？', '提示', {
                              //   closeOnClickModal: false,
                              //   confirmButtonText: '确定',
                              //   cancelButtonText: '取消',
                              //   type: 'warning'
                              // }).then(() => {
                          const params = {
                            agencyId: this.agencyId,
                            menuid: this.menuid,
                          };
                          submit(params)
                            .then((res) => {
                              this.$message({
                                message: "送审成功",
                                type: "success",
                                showClose: true,
                                duration: 4000,
                              });
                              // 刷新数据
                              this.getList();
                              this.$emit("handleSubmitBtnLoading");
                              this.$emit("handleSubmitBtnLoadings");
                            })
                            .catch(() => {
                              this.$emit("handleSubmitBtnLoading");
                          });
                      })
                      .catch(()=>{
                        this.$emit("handleSubmitBtnLoading")
                      })
                  })
                  .catch(() => {
                    this.$emit("handleSubmitBtnLoading");
                  });
              })
              .catch(() => {
                this.$emit("handleSubmitBtnLoading");
              });
          })
          .catch(() => {
            this.$emit("handleSubmitBtnLoading");
          });
          }
      }).catch(() => {
          this.$emit('handleSubmitBtnLoading')
      })


      // }).catch(() => {
      //   this.$emit('handleSubmitBtnLoading')
      // })
    },

    // 撤销送审
    handleRejectSubmit() {
      if (this.total === 0) {
        this.$message({
          message: "没有可撤销送审的数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleRejectSubmitBtnLoading");
        return;
      }
      this.queryAgencyNameAndState()
        .then(() => {
          // 审核后不可撤销送审
          if (this.salaryVerifiedInAgencyCode === "1") {
            this.$message({
              message: "当前单位数据已审核，不可撤销送审！",
              type: "warning",
              showClose: true,
              duration: 4000,
            });
            this.$emit("handleRejectSubmitBtnLoading");
            return;
          }
          // this.$confirm('确定撤销送审吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then(() => {
          const params = { agencyId: this.agencyId, menuid: this.menuid };
          rejectSubmit(params)
            .then((res) => {
              this.$message({
                message: "撤销送审成功",
                type: "success",
                showClose: true,
                duration: 4000,
              });
              // 刷新数据
              this.getList();
              this.$emit("handleRejectSubmitBtnLoading");
            })
            .catch(() => {
              this.$emit("handleRejectSubmitBtnLoading");
            });
        })
        .catch(() => {
          this.$emit("handleRejectSubmitBtnLoading");
        });
      // })
      // .catch(() => {
      //   this.$emit('handleRejectSubmitBtnLoading')
      // })
    },

    // handleInput(e, row, name) {
    //   const regex = /^\d{0,16}\.?\d{0,2}$/
    //   const value = e.value
    //   if (!regex.test(value)) {
    //     row[name] = this.inputList['id' + row.id + '_' + name]
    //       ? this.inputList['id' + row.id + '_' + name]
    //       : '0.00'
    //   } else {
    //     this.inputList['id' + row.id + '_' + name] = value
    //   }
    // },

    // handleChange(val, row, name) {
    //   const regex = /^((0|[1-9][0-9]{0,17})|([0]\.\d{1,2}|[1-9][0-9]{0,15}\.\d{1,2}))$/
    //   const value = val.value
    //   if (!regex.test(value)) {
    //     row[name] = this.changeList['id' + row.id + '_' + name]
    //       ? this.changeList['id' + row.id + '_' + name]
    //       : '0.00'
    //   } else {
    //     this.changeList['id' + row.id + '_' + name] = value
    //   }
    // },

    // 全选
    handleCheckAll(val) {
      const checked = val.checked;
      for (let i = 0; i < this.list.length; i++) {
        this.list[i].check = checked;
      }
      this.checkAll = true;
      this.indeterminate = false;
      this.checkList = [];
      if (checked) {
        for (const item of this.list) {
          if (item.check) {
            this.checkList.push(item);
          }
        }
      }
    },

    // 点击多选按钮
    handleCheck() {
      this.checkList = [];
      const totalCount = this.list.length - 1;
      let isCheckedCount = 0;
      this.list.forEach((item) => {
        if (item.check) {
          this.checkList.push(item);
          isCheckedCount++;
        }
      });
      this.checkAll = totalCount === isCheckedCount;
      this.indeterminate = isCheckedCount > 0 && isCheckedCount < totalCount;
    },
    // 附件方法
    appendixOpen() {
      const that = this;
      const selection = that.checkList;
       if(selection.length>0){
      const arr=[]
      for(let i=0;i<selection.length;i++){
          arr.push(selection[i].personName)
          }
      this.$confirm( "当前操作"+arr+ ' 提示!', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
		that.openenclosure = true;
		const idList = [];
      selection.forEach((item) => {
        idList.push({ id: item.personId });
      });
      that.$refs.enc.appendixOpen(idList,that.openenclosure,undefined,this.agencyId)
       }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消上传'
          });
        });
     }else {
          that.openenclosure = false;
		  if (this.isSubmitInAgency === 1) {
        that.openenclosure = false;
      }
          const idList = [];
      selection.forEach((item) => {
        idList.push({ id: item.personId });
      });
         that.$refs.enc.appendixOpen(idList,that.openenclosure,undefined,this.agencyId)
     }
    },
    // 查看详情
    viewInfo(currenRow) {
      const personId = currenRow.personId.replace("noRepeat", "");
      this.$refs.personSalaryInfo.viewInfo(personId, undefined, this.agencyId);
    },
    // 导出
    outPutFile() {
      Object.assign(this.listQuery, this.formData);
      this.listQuery["agencyId"] = this.agencyId;
      outPutSalaryReportList(this.listQuery).then((response) => {
        const link = document.createElement("a");
        const objectUrl = URL.createObjectURL(response);
        link.href = objectUrl;
        link.download = "单位工资编报.xls";
        link.click();
        URL.revokeObjectURL(objectUrl);
      });
    },
    // 上传文件
    uploadExcel(item) {
      const fileObj = item.file;
      // FormData 对象
      const form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      form.append("agencyId", this.agencyId);
      Import(form)
        .then((response) => {
          this.$message({
            showClose: true,
            message: "导入成功",
            type: "success",
            duration: 4000,
          });
          this.dialogImportFormVisible = false;
        })
        .then(() => {
          this.getList();
        });
    },
    // 导入
    importFile() {
      if (this.isSubmitInAgency === 1) {
        this.$message({
          message: "当前单位数据已送审，不可导入！",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        return;
      }
      this.dialogImportFormVisible = true;
    },
    // 树点击
    handleNodeClick(data) {
      this.formData.deptId = data.id;
      this.formData.deptName = data.label;
      if (this.formData.deptName === "组织机构") {
        this.formData.deptId = "";
        this.formData.deptName = "";
      } else {
        this.$refs.selectReport.blur();
      }
    },
    // 清除下拉树选中
    clearHandle() {
      this.formData.deptName = "";
      this.formData.deptId = "";
      this.defaultExpandedKey = [];
    },
    // 获取数内容
    getTree() {
      getDepartmentTree(this.listQuery).then((response) => {
        this.listTree = response.data;
      });
    },
    nextInput(event) {
      const vElem = event.target;
      const inputArray = document.getElementsByClassName("vxe-input--inner");
      for (let index = 0; index < inputArray.length; index++) {
        if (vElem === inputArray[index]) {
          inputArray[index + 1].focus();
          return;
        }
      }
    },
    meanNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
       return count / list.length
    },
    sumNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
        })
      return count
    },
    footerMethod ({ columns, data }) {
      
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('合计')
        } else {
          let sumCell = null
          if (columnIndex>6) {
             sumCell = this.sumNum(data, column.property)
            sumCell = Number(sumCell).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
          }else{
            sumCell=''
          }
          sums.push(sumCell)
        }
      })
              // 返回一个二维数组的表尾合计
      return [sums]
   }
    
  }
}
</script>
<style lang="scss">
.el-message-box {
    width:auto;
    overflow-y: scroll;
    vertical-align: middle;
    background-color: #FFFFFF;
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    font-size: 18px;
    -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    text-align: left;
    overflow: hidden;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
}
.el-message-box--center .el-message-box__message {
     max-width : 800px;
     max-height : 500px;
         overflow-y:auto
}
</style>
<style lang="scss" scoped>
.file-logo {
  color: #0b68ea;
  font-weight: 900;
  font-size: 18px;
}
.warn-font-color {
  color: red;
}

.el-table {
  .cell {
    .el-table__expand-icon {
      display: none;
    }

    .el-table__indent {
      padding-left: 0 !important;
    }

    .el-table__placeholder {
      display: none;
    }
  }
}

/** 文本框高度 **/
.el-input:not(.el-pagination__editor):not(.el-input--mini) {
  width: 130px;
  height: 40px !important;
}

// 表格小三角
// ::v-deep.el-table .el-table__expand-icon {
//   display: inline-block;
//   width: 20px;
//   line-height: 20px;
//   height: 20px;
//   text-align: center;
//   margin-right: 3px;
//   display: none;
// }

//::v-deep深度作用选择器混用本地和全局样式
::v-deep.el-input:not(.el-pagination__editor):not(.el-input--mini)
  .el-input__inner {
  height: 35px;
  text-align: right !important;
}
.agencyTree {
    .el-input {
      width: 100% !important;
      height: 40px !important;
      .el-input__inner{
        height: 35px;
      }
    }
}
</style>
